package com.example.contller;

import com.alibaba.fastjson.JSONObject;
import com.example.dao.entity.SysUser;
import com.example.shiro.utils.RequestUtils;
import org.apache.commons.lang3.StringUtils;
import org.apache.shiro.SecurityUtils;
import org.apache.shiro.authc.AuthenticationException;
import org.apache.shiro.authc.ExcessiveAttemptsException;
import org.apache.shiro.authc.IncorrectCredentialsException;
import org.apache.shiro.authc.LockedAccountException;
import org.apache.shiro.authc.UnknownAccountException;
import org.apache.shiro.authc.UsernamePasswordToken;
import org.apache.shiro.crypto.hash.Md5Hash;
import org.apache.shiro.subject.Subject;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RestController;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;


@RestController
@RequestMapping(value = "/auth")
public class LoginController {
	private static final Logger logger = LoggerFactory.getLogger(LoginController.class);
	
//    @RequestMapping(value = "/login", method = RequestMethod.POST)
//    public String submitLogin(String username, String password, HttpServletRequest request) {
//        try {
//        	String pwd = new Md5Hash(password, "quqi",1024).toBase64();//加盐
//            UsernamePasswordToken token = new UsernamePasswordToken(username, pwd);
//            Subject subject = SecurityUtils.getSubject();
//            subject.login(token);
//            SysUser user = (SysUser) subject.getPrincipal();
//        } catch (LockedAccountException e) {
//            request.setAttribute("msg", "账户已被禁用");
//            return "账户已被禁用";
//        } catch (IncorrectCredentialsException e) {
//            request.setAttribute("msg", "用户名或密码错误");
//            return "用户名或密码错误";
//        }
//
//        // 执行到这里说明用户已登录成功
//        return "登录成功";
//    }
    
    @RequestMapping(value = "/login", method = RequestMethod.POST)
	public String login(String username, String password,HttpServletRequest request, HttpServletResponse response) {

		JSONObject json = new JSONObject();
//		String username = user.getUsername();
		String pwd = new Md5Hash(password, "quqi",1024).toBase64();//加盐
		UsernamePasswordToken token = new UsernamePasswordToken(username, pwd);
		// token.setRememberMe(true);
		// 获取当前的Subject
		Subject currentUser = SecurityUtils.getSubject();
		

		try {
			// 在调用了login方法后,SecurityManager会收到AuthenticationToken,并将其发送给已配置的Realm执行必须的认证检查
			// 每个Realm都能在必要时对提交的AuthenticationTokens作出反应
			// 所以这一步在调用login(token)方法时,它会走到MyRealm.doGetAuthenticationInfo()方法中,具体验证方式详见此方法
			logger.info("对用户[" + username + "]进行登录验证..验证开始");
			currentUser.login(token);
			json.put("code", 1);
			json.put("msg", "登录成功");
			logger.info("对用户[" + username + "]进行登录验证..验证通过");
			
		} catch (UnknownAccountException uae) {
			logger.info("对用户[" + username + "]进行登录验证..验证未通过,未知账户");
			json.put("code", 0);
			json.put("msg", "账户不存在");
//			redirectAttributes.addFlashAttribute("message", "账户不存在");
		} catch (IncorrectCredentialsException ice) {
			logger.info("对用户[" + username + "]进行登录验证..验证未通过,错误的凭证");
			json.put("code", 0);
			json.put("msg", "密码不正确");
//			redirectAttributes.addFlashAttribute("message", "密码不正确");
		} catch (LockedAccountException lae) {
			logger.info("对用户[" + username + "]进行登录验证..验证未通过,账户已锁定");
			json.put("code", 0);
			json.put("msg", "账户已锁定");
//			redirectAttributes.addFlashAttribute("message", "账户已锁定");
		} catch (ExcessiveAttemptsException eae) {
			logger.info("对用户[" + username + "]进行登录验证..验证未通过,错误次数过多");
			json.put("code", 0);
			json.put("msg", "用户名或密码错误次数过多");
//			redirectAttributes.addFlashAttribute("message", "用户名或密码错误次数过多");
		} catch (AuthenticationException ae) {
			// 通过处理Shiro的运行时AuthenticationException就可以控制用户登录失败或密码错误时的情景
			logger.info("对用户[" + username + "]进行登录验证..验证未通过,堆栈轨迹如下");
			ae.printStackTrace();
			json.put("code", 0);
			json.put("msg", "用户名或密码不正确");
		}
		// 验证是否登录成功
		if (currentUser.isAuthenticated()) {
			logger.info("用户[" + username + "]登录认证通过(这里可以进行一些认证通过后的一些系统参数初始化操作)");
		}
		return JSONObject.toJSONString(json);
	}


    @RequestMapping(value = "/login", method = RequestMethod.GET)
    public String loginPage() {
        return "login登录";
    }

    @RequestMapping(value = "/index", method = RequestMethod.GET)
    public String loginSuccessMessage(HttpServletRequest request) {
        String username = "未登录";
        SysUser currentLoginUser = RequestUtils.currentLoginUser();
        if (currentLoginUser != null && StringUtils.isNotEmpty(currentLoginUser.getUserName())) {
            username = currentLoginUser.getUserName();
        } else {
            return "被踢出或登录过期";
        }
        request.setAttribute("username", username);
        return "主页面";
    }

    //被踢出后跳转的页面
    @RequestMapping(value = "/kickout", method = RequestMethod.GET)
    public String kickOut() {
        return "kickout";
    }
}
